<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:class:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:class:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:class:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:class:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="班级学生" align="center" prop="students" >
        <template #default="scope">
          <el-tag v-for="student in scope.row.students" style="margin-right:5px">
            {{ student.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:class:edit']">修改</el-button>
          <el-button link type="primary" icon="Edit" @click="handleEditStudents(scope.row)" v-hasPermi="['system:class:edit']">编辑学生</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:class:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="classRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--  班级学生管理  -->
    <el-dialog :title="titleOfManageClass" v-model="openOfStudents" width="700px" append-to-body>
      <el-form ref="classStudentsRef" :model="studentForm" :rules="rulesOfManageClass" label-width="80px">
        <el-transfer
            v-model="studentForm.students"
            :data="studentsData"
            :titles="['未选择班级的学生', '本班学生']"
        />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitStudentsForm">确 定</el-button>
          <el-button @click="cancelStudentsForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Class">
import { listClass, getClass, delClass, addClass, updateClass } from "@/api/system/class"
import { getMyClassStudentsIds, getNoClassAndThisClassStudentsInfo, updateThisClassStudents } from "@/api/system/class"

const { proxy } = getCurrentInstance()

const classList = ref([])
const open = ref(false)
const openOfStudents = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const titleOfManageClass = ref("班级学生管理")
const studentsData = ref([])

const data = reactive({
  form: {},
  studentForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    className: null,
  },
  rules: {
  },
  rulesOfManageClass: {
  }
})

const { queryParams, form, rules, studentForm, rulesOfManageClass } = toRefs(data)

/** 查询班级信息列表 */
function getList() {
  loading.value = true
  listClass(queryParams.value).then(response => {
    classList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}
// 取消按钮
function cancelStudentsForm() {
  openOfStudents.value = false
  resetStudents()
}


// 表单重置
function reset() {
  form.value = {
    id: null,
    className: null,
    createTime: null
  }
  proxy.resetForm("classRef")
}

// 表单重置
function resetStudents() {
  studentForm.value = {
    classId : null,
    students: []
  }
  proxy.resetForm("classStudentsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加班级信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getClass(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改班级信息"
  })
}
/** 修改按钮操作 */
function handleEditStudents(row) {
  resetStudents()

  // 1.查询本班学生id集合
  getMyClassStudentsIds(row.id).then(response => {
    // console.log(response.data)
    studentForm.value = {
      classId : row.id,
      students: response.data
    }

    //2.查询没有班级的学生信息和本班级的学生信息的集合
    getNoClassAndThisClassStudentsInfo(row.id).then(response1 => {
      studentsData.value = response1.data;
      //对话框显示
      openOfStudents.value = true
    })
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["classRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateClass(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addClass(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}
/** 提交学生管理提交按钮 */
function submitStudentsForm() {
  proxy.$refs["classStudentsRef"].validate(valid => {
    if (valid) {
      console.log(studentForm.value)
      /**
       * 做法1：删除原来的本班学生，然后再把新的本班学生的id集合的所有学生班级id改为本班✅
       * 做法2，将老学生ids集合和新学生的ids集合进行比较，删除在老集合中有，新集合中没有的学生，并且新增老集合中没有，新集合中有的学生
       */
      const newStudentIds = studentForm.value.students;
      const classId = studentForm.value.classId
      console.log(newStudentIds)
      console.log(classId)
      updateThisClassStudents({ids: newStudentIds, classId: classId}).then(response => {
        openOfStudents.value = false
        getList()
      })
    }
  })
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除班级信息编号为"' + _ids + '"的数据项？').then(function() {
    return delClass(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/class/export', {
    ...queryParams.value
  }, `class_${new Date().getTime()}.xlsx`)
}



getList()
</script>
